﻿using Microsoft.Extensions.Logging;
using ORS.OrderRobot.IOC;
using ORS.OrderRobot.ServiceContracts;

namespace ORS.OrderRobot.Service.Worker
{
    /// <summary>
    /// 提前设置购物车依赖信息
    /// </summary>
	public class ShoppingDepInfoWorker : CronWorkerBase, IBackgroundWorker, IScoped
    {
        private readonly ILogger<ShoppingDepInfoWorker> _logger;
        private readonly IAccountLoginService _accountLoginService;
        private readonly IShoppingService _shoppingService;
        public ShoppingDepInfoWorker(
            ILogger<ShoppingDepInfoWorker> logger,
            IAccountLoginService accountLoginService,
            IShoppingService shoppingService
        )
		{
            _logger = logger;
            _accountLoginService = accountLoginService;
            _shoppingService = shoppingService;
        }

        public override string Name => nameof(ShoppingDepInfoWorker);

        public override async Task<string> GetCronExpressionAsync()
        {
            await Task.CompletedTask;
            //凌晨5点执行
            return "0 5 * * *";
        }
        protected override async Task DoWorkAsync()
        {
            try
            {
                var userList = await _accountLoginService.AutoLoginAsync();
                if (userList == null || !userList.Any())
                {
                    _logger.LogError("没有已登录的用户");
                    return;
                }
                var tasks = userList.Select(async email =>
                {
                    await _shoppingService.SetShoppingDepInfoAsync(email);
                });
                await Task.WhenAll(tasks);
            }
            catch { }

        }

        protected override async Task<TimeOnly?[]> GetTimeRange()
        {
            return await Task.FromResult<TimeOnly?[]>(null);
        }
    }
}

